﻿using EasyAdmin.Domain.Entities.Systems;
using EasyCore.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using static System.Formats.Asn1.AsnWriter;

namespace EasyAdmin.Web.ApiCollectors
{
    /// <summary>
    /// API收集器扩展类
    /// </summary>
    public static class ApiCollectorExtensions
    {
        /// <summary>
        /// 添加相关服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="action"></param>
        public static void AddApiCollectorServices(this IServiceCollection services,Action<ApiCollectorOptions> action) { 
            services.AddScoped<IApiCollector, ApiCollector>();
            ApiCollectorOptions options = new ApiCollectorOptions();
            services.AddSingleton<ApiCollectorOptions>(options);
            if (action != null) {
                action(options);
            }
        }

        /// <summary>
        /// 收集API信息：扩展方法
        /// </summary>
        /// <param name="action"></param>
        public static void CollectApis(this WebApplication app)
        {
            // 执行API收集
            using (var scope = app.Services.CreateScope())
            {
                var collector = scope.ServiceProvider.GetRequiredService<IApiCollector>();        
                var inputEndpoints = collector.CollectApisAsync().Result;
                var apiEndpointRepao = scope.ServiceProvider.GetRequiredService<ISqlSugarRepository<SysApiEndpoint>>();
                var apiEndpoints = apiEndpointRepao.ToList();
                List<long> updatedIds = new List<long>();
                List<long> deletedIds = new List<long>();
                var insertEndpoints = new List<SysApiEndpoint>();
                if (inputEndpoints != null && inputEndpoints.Any())
                {
                    foreach (var endpoint in inputEndpoints)
                    {
                        string routhHash = string.Format("{0}:{1}", endpoint.HttpMethod, endpoint.RouteTemplate).ToSHA256String();//计算路由哈希
                        var temp = apiEndpoints.FirstOrDefault(m => m.RouthHash == routhHash);
                        if (temp != null)
                        {
                            updatedIds.Add(temp.Id);                       
                        }
                        else 
                        {
                            endpoint.RouthHash = routhHash;
                            insertEndpoints.Add(endpoint);
                        }
                    }
                }
                foreach (var endpoint in apiEndpoints)
                {
                    if (updatedIds.Exists(m => m == endpoint.Id))
                    {
                        endpoint.IsDeleted = false;
                        apiEndpointRepao.Update(endpoint); //更新
                    }
                    else  apiEndpointRepao.Delete(endpoint);    //删除         
                }
                if(insertEndpoints.Any())
                apiEndpointRepao.Insert(insertEndpoints); //插入
            }
   
        }
    }
}
